package com.java.base.javabase.thread.pool.dataSummary;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Function;

/**
 *@ClassName DataSummaryThread
 *@Description TODO 多个线程处理业务，最后汇总所有线程的执行结果
 *@Author FangShanShan
 *@Date 2020/8/7 10:49
 *@Version 1.0
 */
@Slf4j
public class DataSummaryThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Integer taskCount = 10;
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<Integer>> dealTaskFutureList = new ArrayList<>();
        for(int i = 0 ; i < taskCount; i ++) {
            Future<Integer> future = executorService.submit(new DealTask(i + 1));
            dealTaskFutureList.add(future);
        }

        int total = 0; // 汇总结果
        int doneTask = 0; // 完成的任务数量

        while (! dealTaskFutureList.isEmpty()) {
            Iterator<Future<Integer>> iterator = dealTaskFutureList.iterator();
            while(iterator.hasNext()){
                Future<Integer> nextRecord = iterator.next();
                if(nextRecord.isDone()) {
                    doneTask ++;
                    Integer response = nextRecord.get();
                    total += response;
                    iterator.remove();
                }

                log.info("完成任务量：" + doneTask + " 此时计算结果为：" + total);
                Thread.sleep(3000);
            }
        }
        executorService.shutdown();
    }



}
